package com.wp.基本算法.排序;

import java.util.Arrays;

/**
 * Created by 王萍 on 2017/8/23 0023.
 */
//第一次遍历找出最小的放在array[0].
//第二次遍历找出最小的放在array[1].
//第三次遍历找出最小的放在array[2].依次类推........
public class 选择排序 {

    public static void main(String[] args) {
//        int[] numbers = new int[]{2, 3, 5, 1, 4, 9, 6};
//        Comparable[] numbers = new Comparable[]{2, 3, 5, 1, 4, 9, 6};
//        selectSort(numbers);
//        Arrays.stream(numbers).forEach(number -> System.out.print(number + " "));
        Comparable[] chars = new Comparable[]{'w','a','n','g','p','i','n','g'};
        selectSort(chars);
        Arrays.stream(chars).forEach(number -> System.out.print(number + " "));
    }

/**
 * 入参仅为int数组
 */
//    public static int[] selectSort(int[] numbers) {
//        int length = numbers.length;
//        int tmp;
//        for (int i = 0; i < length; i++) {
//            int min = i;
//            for (int j = i + 1; j < length; j++) {
//                if (numbers[min] > numbers[j]) min = j;
//            }
//            tmp = numbers[i];
//            numbers[i] = numbers[min];
//            numbers[min] = tmp;
//        }
//        return numbers;
//    }

    /**
     * 入参为任何实现了Comparable类型的对象数组
     */
    public static Comparable[] selectSort(Comparable[] array) {
        int length = array.length;
        Comparable tmp;
        for (int i = 0; i < length; i++) {
            int min = i;
            for (int j = i + 1; j < length; j++) {
                if (array[min].compareTo(array[j]) > 0) min = j;
            }
            tmp = array[i];
            array[i] = array[min];
            array[min] = tmp;
        }
        return array;
    }
}
